/**
 * Created by Delicate on 2018/1/3.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    Image,
    Text,
    FlatList,
    TouchableOpacity,
    DeviceEventEmitter,
    ActivityIndicator
} from 'react-native';

import NavBar from '../../components/NavBarView'
import LoadedAll from '../../components/ListLoadedAllView'
import SystemService from '../../services/System'
import Constants from '../../config/Constants'

let _self;

class Views extends React.Component {

    constructor(props) {
        super(props)
        _self = this;
        this.state = {
            system: {
                content: '',
                date: '',
                isNew: false
            },
            demands: [],
            pageNumber: 1,
            pageSize: 10,
            refreshing: false,
            pulling: false,
            lastPage: false
        };
        this._loadLock = false;
    }

    componentWillMount() {

    }

    componentDidMount() {
        _self.refresh();
    }

    async refresh() {
        if (!_self._loadLock && !_self.state.refreshing) {
            _self._loadLock = true;
            _self.setState({
                refreshing: true
            });
            const {result, message, data} = await SystemService.messageList({
                params: {
                    pageNumber: 1,
                    pageSize: _self.state.pageSize
                }
            });
            DeviceEventEmitter.emit(Constants.LISTENER_MESSAGES);
            if (result) {
                const page = data.page;
                _self.setState({
                    system: data.system,
                    demands: page.list,
                    pageNumber: 1,
                    lastPage: page.lastPage,
                });
            } else {
                Toast.show(message);
            }
            setTimeout(()=>{
                _self._loadLock = false;
                _self.setState({
                    refreshing: false
                });
            },layout.REFRESH_DELAY_TIME);
        }
    }

    async pull(pageNumber) {
        if (!_self._loadLock && !_self.state.pulling && !_self.state.lastPage && pageNumber && pageNumber !== this.state.pageNumber) {
            _self._loadLock = true;
            _self.setState({
                pulling: true
            });
            const {result, message, data} = await SystemService.messageList({
                params: {
                    pageSize: _self.state.pageSize,
                    pageNumber
                }
            });
            if (result) {
                const page = data.page;
                _self.setState({
                    demands: [
                        ..._self.state.demands,
                        ...page.list
                    ],
                    pageNumber: page.pageNumber,
                    lastPage: page.lastPage
                });
            } else {
                Toast.show(message);
            }
            setTimeout(()=>{
                _self._loadLock = false;
                _self.setState({
                    pulling: false
                });
            },1500)
        }
    }

    skip(path,params) {
        _self.props.navigation.navigate(path,params);
        _self.refresh();
    }

    render() {
        return (
            <View style={base.baseOuter}>
                <NavBar host={this} title="消息"/>
                <FlatList
                    onRefresh={()=>this.refresh()}
                    refreshing={this.state.refreshing}
                    onEndReached={() => this.pull(this.state.pageNumber + 1)}
                    onEndReachedThreshold={0.5}
                    ListHeaderComponent={() => {
                        return (
                            <TouchableOpacity onPress={() => this.skip('SystemMessage')}
                                              activeOpacity={layout.TOUCH_OPACITY_ACTIVE}>
                                <View style={[base.rowCC, styles.card]}>
                                    <View style={[base.rowCC, styles.inner]}>
                                        <Image
                                            resizeMode={'contain'}
                                            source={require('../../sources/icon_message_system.png')}
                                            style={styles.icon}/>
                                        <View style={styles.textBox}>
                                            <View style={[base.rowCC, styles.titleBox]}>
                                                <Text allowFontScaling={false} style={styles.title}>系统消息</Text>
                                                <Text allowFontScaling={false} style={styles.date}>{this.state.system.date}</Text>
                                            </View>
                                            <View style={[base.rowCC, styles.contentBox]}>
                                                <Text allowFontScaling={false} style={styles.content}>{this.state.system.content || '暂无系统消息'}</Text>
                                                {
                                                    this.state.system.isNew ? <View style={styles.point}/> : <View/>
                                                }
                                            </View>
                                        </View>
                                    </View>
                                </View>
                            </TouchableOpacity>
                        )
                    }}
                    data={this.state.demands}
                    keyExtractor={(item, index) => index}
                    renderItem={({item}) => {
                        return (
                            <TouchableOpacity
                                onPress={()=>this.skip('Message',{id:item.id})}
                                activeOpacity={layout.TOUCH_OPACITY_ACTIVE}>
                                <View style={[base.rowCC, styles.card]}>
                                    <View style={[base.rowCC, styles.inner, styles.topLine]}>
                                        <Image
                                            resizeMode={'contain'}
                                            source={require('../../sources/icon_message_custom.png')}
                                            style={styles.icon}/>
                                        <View style={styles.textBox}>
                                            <View style={[base.rowCC, styles.titleBox]}>
                                                <Text allowFontScaling={false} style={styles.title}>需求沟通</Text>
                                                <Text allowFontScaling={false} style={styles.date}>{item.create_date}</Text>
                                            </View>
                                            <View style={[base.rowCC, styles.subBox]}>
                                                <Text allowFontScaling={false} style={styles.subTitle}>{item.asset_name}</Text>
                                                {
                                                    item.is_read === '01' ? <View style={styles.point}/> : <View/>
                                                }
                                            </View>
                                            <Text
                                                style={styles.content}>{item.chat_send_name + '：' + item.message_content}</Text>
                                        </View>
                                    </View>
                                </View>
                            </TouchableOpacity>
                        )
                    }}
                    ListFooterComponent={() => {
                        if (this.state.lastPage && this.state.demands.length > 0) {
                            return (
                                <LoadedAll/>
                            )
                        } else {
                            return (
                                <View>
                                    <ActivityIndicator animating={this.state.pulling}/>
                                </View>
                            )
                        }
                    }}
                />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    outer: {
        backgroundColor: layout.MAIN_BACKGROUND_COLOR
    },
    container: {
        flex: 1,
        width: layout.MAX_WIDTH,
    },
    card: {
        width: layout.MAX_WIDTH,
        backgroundColor: '#fff',
        paddingHorizontal: layout.GAP_HORIZONTAL_MID
    },
    inner: {
        alignItems: 'flex-start',
        paddingVertical: layout.height(30),
    },
    topLine: {
        borderTopColor: '#f2f2f2',
        borderTopWidth: layout.LINE_WIDTH * 2,
    },
    icon: {
        marginTop: layout.GAP_VERTICAL_SMALL,
        marginHorizontal: layout.GAP_HORIZONTAL_MID,
        width: layout.width(64),
        height: layout.height(64),
    },
    textBox: {
        flex: 1,
        paddingHorizontal: layout.GAP_HORIZONTAL_MID
    },
    titleBox: {
        paddingBottom: layout.height(24)
    },
    title: {
        flex: 1,
        color: layout.MAIN_AUX_COLOR,
        fontSize: layout.font(30)
    },
    date: {
        color: '#666666',
        fontSize: layout.font(26)
    },
    contentBox: {},
    content: {
        flex: 1,
        color: '#666666',
        fontSize: layout.font(26)
    },
    point: {
        marginLeft: layout.GAP_HORIZONTAL_SMALL,
        width: layout.width(14),
        height: layout.height(14),
        borderRadius: layout.height(14),
        backgroundColor: '#fd0000'
    },
    subBox: {
        paddingBottom: layout.height(20)
    },
    subTitle: {
        flex: 1,
        color: '#666666',
        fontSize: layout.font(26)
    },
})

//路由
const MessageList = {
    screen: Views,
    navigationOptions: {
        header: null,
    },
    name: 'MessageList',
    sign: true
};

export default MessageList;